// newapi/todo.js
var express = require('express');
var router = express.Router();

const todoModel = require('../../models/newmodels/todoRoutes'); // 确保路径正确

// 创建一个新的待办事项
router.post('/todos', function (req, res, next) {
  const { description } = req.body;
  const newTodo = new todoModel({
    description
  });

  newTodo.save()
    .then((data) => {
      console.log('待办事项创建成功:', data);
      res.json({
        code: 200,
        msg: '待办事项创建成功',
        data: data
      });
    })
    .catch((err) => {
      console.error('Error creating todo:', err);
      res.status(500).json({
        code: 500,
        msg: '服务器内部错误',
        data: err.message
      });
    });
});

// 获取所有待办事项
router.get('/findTodos', function (req, res, next) {
  todoModel.find()
    .then((todos) => {
      console.log('查询到的待办事项:', todos);
      res.json({
        code: 200,
        msg: '查询成功',
        data: todos
      });
    })
    .catch((err) => {
      console.error('Error during todo query:', err);
      res.status(500).json({
        code: 500,
        msg: '服务器内部错误',
        data: err.message
      });
    });
});

//条件查询
// 条件查询：查询 completed 为 false 的待办事项
router.get('/findTodoByCom', function (req, res, next) {
  todoModel.find({ completed: false })
    .then((todos) => {
      console.log('查询到的待办事项:', todos);
      res.json({
        code: 200,
        msg: '查询成功',
        data: todos
      });
    })
    .catch((err) => {
      console.error('Error during todo query:', err);
      res.status(500).json({
        code: 500,
        msg: '服务器内部错误',
        data: err.message
      });
    });
});

// -----------修改机器的状态----------
router.put('/upDateTodos', async (req, res) => {
  try {

    const { _id, completed } = req.body;
    console.log(req.body);


    if (!_id || !completed) {
      return res.status(400).json({ code: 400, msg: '参数不合法', data: null });
    }

    const updatedTodo = await todoModel.findByIdAndUpdate(_id, { completed }, { new: true });
    if (!updatedTodo) {
      return res.status(404).json({ code: 404, msg: '待办事项不存在', data: null });
    }

    res.json({ code: 200, msg: '更新成功', data: updatedTodo });
  } catch (err) {
    res.status(500).json({ code: 500, msg: '服务器错误', data: err.message });
  }
});

router.delete('/deleteTodos', async (req, res) => {
  try {
    const { _id } = req.body;

    if (!_id) {
      return res.status(400).json({ code: 400, msg: '参数不合法', data: null });
    }

    const deletedTodo = await todoModel.findByIdAndDelete(_id);
    if (!deletedTodo) {
      return res.status(404).json({ code: 404, msg: '待办事项不存在', data: null });
    }

    res.status(200).json({ code: 200, msg: '删除成功', data: deletedTodo });
  } catch (err) {
    res.status(500).json({ code: 500, msg: '服务器错误', data: err.message });
  }
});



module.exports = router;